package it.tcm.TeacherClassMate.action;

import it.tcm.TeacherClassMate.beans.DisequationBean;
import it.tcm.TeacherClassMate.beans.EquationBean;
import it.tcm.TeacherClassMate.facade.DisequationManageBase;
import it.tcm.TeacherClassMate.facade.EquationManageBase;
import it.tcm.TeacherClassMate.form.DisequationUploadForm;
import it.tcm.TeacherClassMate.form.EquationUploadForm;
import it.tcm.TeacherClassMate.form.GeneralForm;
import it.tcm.TeacherClassMate.util.Util;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;



public class StartLoggedAction extends Action {

	// --------------------------------------------------------- Instance Variables

	// --------------------------------------------------------- Methods


	private Logger logger = Logger.getLogger(this.getClass().getName());
	
	/** 
	 * Method execute
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 * 
	 */

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public ActionForward execute(
		ActionMapping mapping,
		ActionForm form,
		HttpServletRequest request,
		HttpServletResponse response) 
	{		
		 logger.info("STARTLOGGED ACTION");			  
		 
		 EquationManageBase emb = new EquationManageBase();
		 DisequationManageBase dmb = new DisequationManageBase();
		 String mode = null;
		 if (form == null) {
			 List<EquationBean> equationBeanList = emb.getAll();
			 request.setAttribute("resultList", equationBeanList);
			 request.setAttribute(Util.FORM_GENERAL, new GeneralForm()); 
		 }
		 else {
			 GeneralForm gform = (GeneralForm)form;	
			 logger.info("gform.getIdtypology() " + gform.getIdtypology());
			 if (gform.getMode() != null) { mode = (String)gform.getMode(); }	
			 logger.info("mode " + mode);	
			 if (mode == null || mode.equals("")) {
				 List<EquationBean> equationBeanList = emb.getAll();
				 request.setAttribute("resultList", equationBeanList);
				 request.setAttribute(Util.FORM_GENERAL, new GeneralForm()); 
			 } else if (mode.equals("MENU")) {
				 if ((gform.getIdtypology() == null || gform.getIdtypology().equals(Util.EQUATIONS_TYPOLOGY))) {
					 // SHOW ALL ABOUT EQUATION TYPOLOGY
					 List<EquationBean> equationBeanList = emb.getAll();
					 request.setAttribute("resultList", equationBeanList);
					 gform =  new GeneralForm();
					 gform.setIdtypology(Util.EQUATIONS_TYPOLOGY);
					 request.setAttribute(Util.FORM_GENERAL,gform);
				 } else if ((gform.getIdtypology() == null || gform.getIdtypology().equals(Util.DISEQUATIONS_TYPOLOGY))) {
					 // SHOW ALL ABOUT DISEQUATION TYPOLOGY
					 List<DisequationBean> disequationBeanList = dmb.getAll();
					 request.setAttribute("resultList", disequationBeanList);
					 gform =  new GeneralForm();
					 gform.setIdtypology(Util.DISEQUATIONS_TYPOLOGY);
					 request.setAttribute(Util.FORM_GENERAL,gform);
				 }
			 } else if (mode.equals("DELETE")) {
				 if ((gform.getIdtypology() == null || gform.getIdtypology().equals(Util.EQUATIONS_TYPOLOGY))) {
					  // DELETE EQUATION
					 logger.info("delete equation");
					  try{
							 String identify = null;
							 Context ctx = new InitialContext();
							 String docxFileDir = (String)ctx.lookup("java:comp/env/docxPath");
							 String equationDocxFileDir = docxFileDir + "//E//";
							 if (gform.getIdentify() != null) { identify = (String)gform.getIdentify(); }
							 logger.info("identify " + identify);
							 EquationBean eq = emb.getEquationById(Integer.valueOf(identify));
							 emb.delete(eq);	    
							 File filedocx = new File(equationDocxFileDir + Util.EQUATION_PREFIX + eq.getId().toString() + ".docx");
							 logger.info("name filedocx = " + equationDocxFileDir + Util.EQUATION_PREFIX + eq.getId().toString() + ".docx");
							 filedocx.delete();
							 logger.info("filedocx deleted");
							 File fileimage = new File(equationDocxFileDir + Util.EQUATION_PREFIX + eq.getId().toString() + ".htm");
							 logger.info("name fileimage = " + equationDocxFileDir + Util.EQUATION_PREFIX + eq.getId().toString() + ".htm");
							 fileimage.delete();
							 logger.info("fileimage deleted");
							 File fileresult = new File(equationDocxFileDir + Util.EQUATION_PREFIX  + eq.getId().toString() + "_result.docx");					   	  	    
							 File fileresult_image = new File(equationDocxFileDir + Util.EQUATION_PREFIX + eq.getId().toString() + "_result.htm");
							 fileresult.delete();
							 logger.info("fileresult deleted");
							 fileresult_image.delete();
							 logger.info("fileresult image deleted");
							 List<EquationBean> equationBeanList = emb.getAll();
							 request.setAttribute("resultList", equationBeanList);
							 request.setAttribute("equationuploadform", new EquationUploadForm());
					  } catch (Exception e) {
						  logger.error("Exception e " + e);
					  }
				 }  else if ((gform.getIdtypology() == null || gform.getIdtypology().equals(Util.DISEQUATIONS_TYPOLOGY))) {
					  // DELETE DISEQUATION
					  logger.info("delete disequation");
					  try{
							 String identify = null;
							 Context ctx = new InitialContext();
							 String docxFileDir = (String)ctx.lookup("java:comp/env/docxPath");
							 String disequationDocxFileDir = docxFileDir + "//D//";
							 if (gform.getIdentify() != null) { identify = (String)gform.getIdentify(); }
							 logger.info("identify " + identify);
							 DisequationBean eq = dmb.getDisequationById(Integer.valueOf(identify));
							 dmb.delete(eq);	    
							 File filedocx = new File(disequationDocxFileDir + Util.DISEQUATION_PREFIX + eq.getId().toString() + ".docx");							      
							 File fileimage = new File(disequationDocxFileDir + Util.DISEQUATION_PREFIX + eq.getId().toString() + ".pdf");					   
							 File fileresult = new File(disequationDocxFileDir + "D" + eq.getId().toString() + "_result.docx");					   	  	    
							 File fileresult_image = new File(disequationDocxFileDir + Util.DISEQUATION_PREFIX + eq.getId().toString() + "_result.pdf");
							 filedocx.delete();
							 fileimage.delete();
							 fileresult.delete();
							 fileresult_image.delete();
							 List<DisequationBean> disequationBeanList = dmb.getAll();
							 request.setAttribute("resultList", disequationBeanList);
							 request.setAttribute("disequationuploadform", new DisequationUploadForm());
					  } catch (Exception e) {
						  logger.error("Exception e " + e);
					  }
				 }
			 	 
			} else if (mode.equals("FIND")) {
				if ((gform.getIdtypology() == null || gform.getIdtypology().equals(Util.EQUATIONS_TYPOLOGY))) {
					 // SEARCH IN THE EQUATION LIST 
			 		 logger.info("FIND");
			 		 gform.setMode("MENU");
			 		 ArrayList<String>  arrayColumns = new ArrayList<String>();
					 ArrayList<String>  arrayOperator = new ArrayList<String>();
					 ArrayList<String>  arrayDataType = new ArrayList<String>();
					 ArrayList<String>  arrayValues  = new ArrayList<String>();
					 
					 if (gform.getGrado() != null && !gform.getGrado().trim().equals("")) {
						 logger.debug("Add criteria: " + "grado" + " --> " + gform.getGrado());
						 arrayColumns.add("grado");
						 if (gform.getGrado_().equals("=")) 
							 arrayOperator.add(Util.SQL_OPERATOR_EQ);
						 else if (gform.getGrado_().equals(">")) 
							 arrayOperator.add(Util.SQL_OPERATOR_GT);
						 else if (gform.getGrado_().equals("<")) 
							 arrayOperator.add(Util.SQL_OPERATOR_LT);
					     arrayDataType.add(Util.SQL_TYPE_INTEGER);
					     arrayValues.add(gform.getGrado());				 
					 }
					 if (gform.getFormanormale() != null) {
						 logger.debug("Add criteria: " + "forma normale" + " --> " + gform.getFormanormale());
						 arrayColumns.add("forma_normale");
					     arrayOperator.add(Util.SQL_OPERATOR_EQ);
					     arrayDataType.add(Util.SQL_TYPE_STRING);
					     arrayValues.add(gform.getFormanormale());				 
					 }	
					 if (gform.getSistema() != null) {
						 logger.debug("Add criteria: " + "sistema" + " --> " + gform.getSistema());
						 arrayColumns.add("sistema");
					     arrayOperator.add(Util.SQL_OPERATOR_EQ);
					     arrayDataType.add(Util.SQL_TYPE_STRING);
					     arrayValues.add(gform.getSistema());				 
					 }	
					 if (gform.getFratta()!= null) {
						 logger.debug("Add criteria: " + "fratta" + " --> " + gform.getFratta());
						 arrayColumns.add("fratta");
					     arrayOperator.add(Util.SQL_OPERATOR_EQ);
					     arrayDataType.add(Util.SQL_TYPE_STRING);
					     arrayValues.add(gform.getFratta());				 
					 }
					 if (gform.getEsponenziale()!= null) {
						 logger.debug("Add criteria: " + "esponenziale" + " --> " + gform.getEsponenziale());
						 arrayColumns.add("esponenziale");
					     arrayOperator.add(Util.SQL_OPERATOR_EQ);
					     arrayDataType.add(Util.SQL_TYPE_STRING);
					     arrayValues.add(gform.getEsponenziale());				 
					 }
					 if (gform.getLogaritmica()!= null) {
						 logger.debug("Add criteria: " + "logaritmica" + " --> " + gform.getLogaritmica());
						 arrayColumns.add("logaritmica");
					     arrayOperator.add(Util.SQL_OPERATOR_EQ);
					     arrayDataType.add(Util.SQL_TYPE_STRING);
					     arrayValues.add(gform.getLogaritmica());				 
					 }
					 if (gform.getIrrazionale()!= null) {
						 logger.debug("Add criteria: " + "irrazionale" + " --> " + gform.getIrrazionale());
						 arrayColumns.add("irrazionale");
					     arrayOperator.add(Util.SQL_OPERATOR_EQ);
					     arrayDataType.add(Util.SQL_TYPE_STRING);
					     arrayValues.add(gform.getIrrazionale());				 
					 }
					 if (gform.getCoefficienti()!= null) {
						 logger.debug("Add criteria: " + "coefficienti" + " --> " + gform.getCoefficienti());
						 arrayColumns.add("coefficienti");
					     arrayOperator.add(Util.SQL_OPERATOR_EQ);
					     arrayDataType.add(Util.SQL_TYPE_STRING);
					     arrayValues.add(gform.getCoefficienti());				 
					 }
					 if (gform.getDifficolta() != null && !gform.getDifficolta().trim().equals("")) {
						 logger.debug("Add criteria: " + "difficolta" + " --> " + gform.getDifficolta());
						 arrayColumns.add("difficolta");
						 if (gform.getDifficolta_().equals("=")) 
							 arrayOperator.add(Util.SQL_OPERATOR_EQ);
						 else if (gform.getDifficolta_().equals(">")) 
							 arrayOperator.add(Util.SQL_OPERATOR_GT);
						 else if (gform.getDifficolta_().equals("<")) 
							 arrayOperator.add(Util.SQL_OPERATOR_LT);
					     arrayDataType.add(Util.SQL_TYPE_INTEGER);
					     arrayValues.add(gform.getDifficolta());				 
					 }
			 		 //Build criteria array
					 if (arrayColumns.size() > 0 ){
						 logger.debug("Build criteria array");
						 ArrayList<ArrayList> criteriaArray = new ArrayList<ArrayList>();	
					  	 criteriaArray.add(arrayColumns);
				    	 criteriaArray.add(arrayOperator);
				    	 criteriaArray.add(arrayDataType);
				    	 criteriaArray.add(arrayValues); 				    	
					     List<EquationBean> rowList = emb.getEquationByCriteria(criteriaArray);	
					     request.setAttribute("resultList", rowList);
				    }else{			    	
						logger.debug("No criteria in array");
						request.setAttribute("warning_find", "Selezionare almeno un criterio di ricerca");
						List<EquationBean> equationBeanList = emb.getAll();
						request.setAttribute("resultList", equationBeanList);
					}	 			
				} else if ((gform.getIdtypology() == null || gform.getIdtypology().equals(Util.DISEQUATIONS_TYPOLOGY))) {
					 // SEARCH IN THE DISEQUATION LIST 
			 		 logger.info("FIND");
			 		 gform.setMode("MENU");
			 		 ArrayList<String>  arrayColumns = new ArrayList<String>();
					 ArrayList<String>  arrayOperator = new ArrayList<String>();
					 ArrayList<String>  arrayDataType = new ArrayList<String>();
					 ArrayList<String>  arrayValues  = new ArrayList<String>();
					 
					 if (gform.getGrado() != null && !gform.getGrado().trim().equals("")) {
						 logger.debug("Add criteria: " + "grado" + " --> " + gform.getGrado());
						 arrayColumns.add("grado");
						 if (gform.getGrado_().equals("=")) 
							 arrayOperator.add(Util.SQL_OPERATOR_EQ);
						 else if (gform.getGrado_().equals(">")) 
							 arrayOperator.add(Util.SQL_OPERATOR_GT);
						 else if (gform.getGrado_().equals("<")) 
							 arrayOperator.add(Util.SQL_OPERATOR_LT);
					     arrayDataType.add(Util.SQL_TYPE_INTEGER);
					     arrayValues.add(gform.getGrado());				 
					 }
					 if (gform.getFormanormale() != null) {
						 logger.debug("Add criteria: " + "forma normale" + " --> " + gform.getFormanormale());
						 arrayColumns.add("forma_normale");
					     arrayOperator.add(Util.SQL_OPERATOR_EQ);
					     arrayDataType.add(Util.SQL_TYPE_STRING);
					     arrayValues.add(gform.getFormanormale());				 
					 }	
					 if (gform.getSistema() != null) {
						 logger.debug("Add criteria: " + "sistema" + " --> " + gform.getSistema());
						 arrayColumns.add("sistema");
					     arrayOperator.add(Util.SQL_OPERATOR_EQ);
					     arrayDataType.add(Util.SQL_TYPE_STRING);
					     arrayValues.add(gform.getSistema());				 
					 }	
					 if (gform.getFratta()!= null) {
						 logger.debug("Add criteria: " + "fratta" + " --> " + gform.getFratta());
						 arrayColumns.add("fratta");
					     arrayOperator.add(Util.SQL_OPERATOR_EQ);
					     arrayDataType.add(Util.SQL_TYPE_STRING);
					     arrayValues.add(gform.getFratta());				 
					 }
					 if (gform.getEsponenziale()!= null) {
						 logger.debug("Add criteria: " + "esponenziale" + " --> " + gform.getEsponenziale());
						 arrayColumns.add("esponenziale");
					     arrayOperator.add(Util.SQL_OPERATOR_EQ);
					     arrayDataType.add(Util.SQL_TYPE_STRING);
					     arrayValues.add(gform.getEsponenziale());				 
					 }
					 if (gform.getLogaritmica()!= null) {
						 logger.debug("Add criteria: " + "logaritmica" + " --> " + gform.getLogaritmica());
						 arrayColumns.add("logaritmica");
					     arrayOperator.add(Util.SQL_OPERATOR_EQ);
					     arrayDataType.add(Util.SQL_TYPE_STRING);
					     arrayValues.add(gform.getLogaritmica());				 
					 }
					 if (gform.getIrrazionale()!= null) {
						 logger.debug("Add criteria: " + "irrazionale" + " --> " + gform.getIrrazionale());
						 arrayColumns.add("irrazionale");
					     arrayOperator.add(Util.SQL_OPERATOR_EQ);
					     arrayDataType.add(Util.SQL_TYPE_STRING);
					     arrayValues.add(gform.getIrrazionale());				 
					 }
					 if (gform.getCoefficienti()!= null) {
						 logger.debug("Add criteria: " + "coefficienti" + " --> " + gform.getCoefficienti());
						 arrayColumns.add("coefficienti");
					     arrayOperator.add(Util.SQL_OPERATOR_EQ);
					     arrayDataType.add(Util.SQL_TYPE_STRING);
					     arrayValues.add(gform.getCoefficienti());				 
					 }
					 if (gform.getDifficolta() != null && !gform.getDifficolta().trim().equals("")) {
						 logger.debug("Add criteria: " + "difficolta" + " --> " + gform.getDifficolta());
						 arrayColumns.add("difficolta");
						 if (gform.getDifficolta_().equals("=")) 
							 arrayOperator.add(Util.SQL_OPERATOR_EQ);
						 else if (gform.getDifficolta_().equals(">")) 
							 arrayOperator.add(Util.SQL_OPERATOR_GT);
						 else if (gform.getDifficolta_().equals("<")) 
							 arrayOperator.add(Util.SQL_OPERATOR_LT);
					     arrayDataType.add(Util.SQL_TYPE_INTEGER);
					     arrayValues.add(gform.getDifficolta());				 
					 }
			 		 //Build criteria array
					 if (arrayColumns.size() > 0 ){
						 logger.debug("Build criteria array");
						 ArrayList<ArrayList> criteriaArray = new ArrayList<ArrayList>();	
					  	 criteriaArray.add(arrayColumns);
				    	 criteriaArray.add(arrayOperator);
				    	 criteriaArray.add(arrayDataType);
				    	 criteriaArray.add(arrayValues); 				    	
					     List<DisequationBean> rowList = dmb.getDisequationByCriteria(criteriaArray);	
					     request.setAttribute("resultList", rowList);
				    }else{			    	
						logger.debug("No criteria in array");
						request.setAttribute("warning_find", "Selezionare almeno un criterio di ricerca");
						List<DisequationBean> disequationBeanList = dmb.getAll();
						request.setAttribute("resultList", disequationBeanList);
					}	 			
				}	 	    						 		 
			}	
		}
	    return mapping.findForward("startlogged"); 
		 
	}
	
	
}